﻿<?php
/*
 * wp_api_post wordpress接口类
 * @author softuses.com
 * @link http://softuses.com
 * <code>
 * define('KC_FILE_COMMAND', '/usr/bin/file -ib "%s"');//用于获取文件类型
 * require_once("class-IXR.php");
 * $username='admin';
 * $password='admin888';
 * $wpsite='http://softuses.com';
 * $wp = new wp_api_post($username, $password, $wpsite);
 * $wp->set_min_max_day(3, 20);//发布时间设置
 *	$posts=array(
 *	 'title'=>'test',
 *	 'categories'=>array('test'),
 *	 'body'=>'test body',
 *	 'keywords'=>array('tag1')
 *	 );
 *	 $wp->wp_post($posts);
 * </code>
 */
class wp_api_post{
    private $username;
    private $password;
    private $wpsite;
    private $xmlclient;
    private $maxday;
    private $minday;
    private $err;
    
    function __construct($username,$password,$wpsite){
        $this->init_base($username, $password, $wpsite);
        $this->maxday=30;
        $this->minday=3;
    }
    function init_base($username,$password,$wpsite){
        $this->username = $username;
        $this->password = $password;
        $this->wpsite = $wpsite;
        $this->xmlclient = $this->wpsite."/xmlrpc.php";
    }
    
    /*
     * 设置发布时间随机天数最小最大值
     * @param int $minday 最小天数
     * @param int $maxday 最大天数
     */
    function  set_min_max_day($minday,$maxday){
        $this->minday = $minday;
        $this->maxday = $maxday;
    }


    /*
     *  返回wordpress中的分类
     *  @return array 返回wp中现在有的分类
     */
    function get_wp_catalog(){
        $client = new IXR_Client($this->xmlclient);
        $params = array(0,$this->username,$this->password);
        if (!$client->query('metaWeblog.getCategories', $params)) {
            $this->err .= 'get catalog error – '.$client->getErrorCode().' : '.$client->getErrorMessage().'\r\n';
            echo $this->err;
            return null;
         }
         $cat_array = $client->getResponse();
         $cat="";
         foreach($cat_array as $arr){
             if($cat==""){
                $cat=$arr['categoryName'];
             }else{
                $cat.="||".$arr['categoryName'];
             }
         }
         $cat_arr=  explode("||", $cat);
//         print_r($cat_arr);
         return $cat_arr;
    }
    
    /*
     * 添加分类
     * @param string $catname 分类名称
     * @return bool 成功返回ture，否则false
     */
    function add_wp_catalog($catname){
        $client = new IXR_Client($this->xmlclient); 
        $categ = array(
        	'name'=>$catname,
            'slug' => $catname,//别名 
            'parent_id' => 0,//父类ID，如果填0则为顶级分类，如果填其他分类ID，则为该类的子类 
            'description' => '' 
        );
        echo "add catalog\r\n";
        $params = array(0,$this->username,$this->password,$categ);
        if (!$client->query('wp.newCategory', $params)) {
             $this->err += 'add wp catalog error – '.$client->getErrorCode().' : '.$client->getErrorMessage().'\r\n';
             echo $this->err;
             return false;
        }
        return true;
    }
    /*
     * 分类不存在自动添加
     * @param array $category 分类数组
     * @return bool 成功返回true，否则返回false
     */
    function wp_catalog($category){
        if( is_array( $category) ){
            $catarray = $this->get_wp_catalog();
            print_r($catarray);
            foreach ($category as $cat) {
                echo $cat;
                if( in_array($cat,$catarray) == false ){//如果不存在，就添加                    
                    if( !$this->add_wp_catalog($cat) );
                        return false;
                }
            }
        }
        return true;
    }
    /*
     *  随机生成发布时间,最后发布时间加根据设定的最大，最小天数。
     *  @return datetime 返回发布时间
     */
    function get_latestpostdate(){
        $Post_MinSeconds = 60*60*24*$this->minday;   //自动定时发布最少时间间隔3天
        $Post_MaxSeconds = 60*60*24*$this->maxday;   //自动定时发布wordpress文章时间最多间隔4天

        $Post_Seconds = mt_rand($Post_MinSeconds, $Post_MaxSeconds); //定时发布时间范围随机天数
        $client = new IXR_Client($this->xmlclient);
        $params = array(0,$this->username,$this->password,1);
        if (!$client->query('metaWeblog.getRecentPosts', $params)) {
              $this->err +='getRecentPosts error – '.$client->getErrorCode().' : '.$client->getErrorMessage().'\r\n'; 
              $latestpostdate = strtotime(date("Y-m-d H:i:s"));
         }elseif ($myresponse = $client->getResponse()) {             
              $object = $myresponse[0]['dateCreated'];   //返回上一次发表文章日期，为IXR_Date对象
              $latestpostdate = mktime($object->hour, $object->minute, $object->second, $object->month, $object->day, $object->year);                  
         }else {
               $latestpostdate = strtotime(date("Y-m-d H:i:s"));
         }
         $posttime = $latestpostdate+$Post_Seconds; //发布时间为举例上一篇发表时间3~4天。
         
         return $posttime;
    }
    
    /*
     * 处理内容中的图片
     * @param string $body 文章中的内容
     * @return string 返回内容处理后的结果
     */
    function get_body($body){
         $imgtag = "<img";
         $srctag = "src";
         $pattern = '/src=\"(.*?)\"/';
         $pattern = "/<img.+src=('|\"|)?(.*)(\\1)([\s].*)?>/ismUe";  //图片代码标签的正则表达式，子模式匹配src地址
         if (strpos($body,$imgtag) && strpos($body,$srctag)) {
            preg_match_all ($pattern,$body,$matches);
            for ($i=0; $i< count($matches[0]); $i++) {
                $url = $matches[2][$i];
                $temp = explode( "/", $url );
                $ext=addslashes(strtolower(substr(strrchr($url, '.'), 1, 10)));//文件类型
                $name = trim( $temp[count( $temp ) - 1] ).".".$ext;//文件名，带扩展    
                
                if(function_exists('mime_content_type')){//只支持php5.2以下 获取文件类型
                  $type = mime_content_type($url);
                }else{
                  $finfo = finfo_open(FILEINFO_MIME);
                  $type = finfo_file($finfo, $url);//获取文件类型
                  finfo_close($finfo);
                }
                
                if(function_exists('file_get_contents')) {
                    $bits = new IXR_Base64( file_get_contents($url));              
                }
                $data = array(
                      'name'=> $name,
                      'type'=> $type,
                      'bits'=> $bits,
                );
                
                $client = new IXR_Client($xmlclient);
                $fileparams = array(0,$username,$password,$data);
                if (!$client->query('metaWeblog.newMediaObject', $fileparams)) {
                      $this->err += 'upload file error – '.$client->getErrorCode().' : '.$client->getErrorMessage().'\r\n';
                      $returnurl="";
                } elseif ($client->getResponse()) {
                      $response = $client->getResponse();
                      $returnurl = $response['url'];
                }
                
                if( $returnurl != ""){
                    $body = str_replace($imgsrc,$returnurl,$body);  //记得给$body赋值
                }
              }
          }
          return $body;
    }
    
    /*
     *  添加文章
     *  @param array $post 文章字段数组
     *  @return bool 成功返回true 否则 false 
     */
    function add_wp_post($post){
         /*发表文章*/
        $content = array(
         "title"=>$post['title'],
         "description"=>$post['body'],
         "mt_allow_comments"=>1,  // 1 to allow comments
         "mt_allow_pings"=>0,  // 1 to allow trackbacks
         "post_type"=>'post',
         "date_created_gmt"=> new  IXR_Date(time()),
         "dateCreated"=>$post['posttime'],//要实时的发布的可以禁掉这字段
         "categories"=>$post['categories'],
         "mt_keywords"=>$post['keywords']
          // 'enclosure'=>$enclosure,这只用于在自定义区域上传音乐等资源，改用metaWeblog.newMediaObject上传
          // 'custom_fields' =>  array($customfields)
         );
        
        $draft = $post["Draft"];
        $draft = ($draft==null)?false:true;
          // Create the client object
          $client = new IXR_Client($this->xmlclient);
          $params = array(0,$this->username,$this->password,$content,$draft); // Last parameter is ‘true’ which means post immideately, to save as draft set it as ‘false’
          // Run a query for PHP
          if (!$client->query('metaWeblog.newPost', $params)) {
                $this->err +='add wp post error – '.$client->getErrorCode().' : '.$client->getErrorMessage().'\r\n';
                return false;
          }
          return true;
    }
    
    /*
     * 发布文章
     * @param array $post 文章字段数组
     */
    function wp_post( $post ){
        $this->err = '';
//         if( !$this->wp_catalog( $post['categories'] )){//分类处理
//             echo "no category";
//             return false;
//         }
      
        $post['posttime'] = $this->get_latestpostdate();//生成发布时间
       
        $post['body'] = $this->get_body($post['body']);//上传内容中的图片
        
        return $this->add_wp_post($post);//发布文章
        
    }
}

?>

